﻿/*
 * ©2009-2010 XELF
 * http://xelf.info
 */

#if XNA || WINDOWS_PHONE
using Microsoft.Xna.Framework;
#endif

namespace XELF.Framework {

	/// <summary>
	/// 衝突判定用の面
	/// </summary>
	public partial class BoundingFace {
		PluckerLine[] Lines;
		Plane Plane;

		/// <summary>
		/// 頂点群を角とする多角形を作る。
		/// ただし、最後-0-1のインデックスの頂点からなる三角形の面を、多角形の平面とみなす。
		/// </summary>
		/// <param name="points"></param>
		/// <returns></returns>
		public static BoundingFace CreateFromPoints(params Vector3[] points) {
			BoundingFace result = new BoundingFace {
				Lines = new PluckerLine[points.Length],
				Plane = new Plane(points[0], points[1], points[2]),
			};
			for (int h = points.Length - 1, i = 0; i < points.Length; h = i, i++) {
				result.Lines[i] = PluckerLine.CreateFromPointToPoint(points[h], points[i]);
			}
			return result;
		}

		/// <summary>
		/// 交差を確認する。
		/// </summary>
		/// <param name="ray"></param>
		/// <param name="rayLine"></param>
		/// <param name="distance"></param>
		public void Intersects(ref Ray ray, ref PluckerLine rayLine, out float? distance) {
			int front = 0, back = 0;
			for (int i = 0; i < Lines.Length; i++) {
				float side;
				PluckerLine.Side(ref rayLine, ref Lines[i], out side);
				front += (side >= 0) ? 1 : 0;
				back += (side <= 0) ? 1 : 0;
			}
			if (front < Lines.Length && back < Lines.Length) {
				distance = null;
				return;
			}
			ray.Intersects(ref Plane, out distance);
			return;
		}
	}

}